import tkinter as tk
from tkinter import ttk, scrolledtext, messagebox
from datetime import datetime
import threading
import queue
import time
import random

class ClashManagerApp:
    def __init__(self, root):
        self.root = root
        self.root.title("部落冲突管理工具 - 动态日志版")
        self.root.geometry("800x600")

        # 日志消息队列（线程安全）
        self.log_queue = queue.Queue()

        # 主布局
        self.setup_top_frame()
        self.setup_log_frame()

        # 启动日志检查定时器
        self.check_log_queue()

    def setup_top_frame(self):
        """顶部区域：玩家数据 + 配置"""
        top_frame = ttk.Frame(self.root)
        top_frame.pack(fill="both", expand=True, padx=10, pady=5)

        # 左上：玩家数据
        self.setup_player_data_frame(top_frame)
        
        # 右上：配置选项
        self.setup_config_frame(top_frame)

    def setup_player_data_frame(self, parent):
        """左上区域：玩家数据"""
        player_frame = ttk.LabelFrame(parent, text="玩家数据", padding=10)
        player_frame.grid(row=0, column=0, sticky="nsew", padx=5, pady=5)

        # 玩家基础信息（示例数据）
        info_labels = [
            ("玩家ID:", "Player#1234"),
            ("等级:", "200"),
            ("英雄等级:", "女王:65 蛮王:60"),
            ("金币:", "10,000,000"),
            ("圣水:", "8,500,000"),
            ("黑油:", "150,000"),
            ("今日获取:", "金币:500K | 圣水:300K | 黑油:5K")
        ]

        for i, (label_text, value_text) in enumerate(info_labels):
            ttk.Label(player_frame, text=label_text).grid(row=i, column=0, sticky="w")
            ttk.Label(player_frame, text=value_text).grid(row=i, column=1, sticky="w")

    def setup_config_frame(self, parent):
        """右上区域：配置选项"""
        config_frame = ttk.LabelFrame(parent, text="配置选项", padding=10)
        config_frame.grid(row=0, column=1, sticky="nsew", padx=5, pady=5)

        # 模式选择
        ttk.Label(config_frame, text="模式:").grid(row=0, column=0, sticky="w")
        self.mode_var = tk.StringVar(value="打鱼")
        ttk.Combobox(
            config_frame, 
            textvariable=self.mode_var,
            values=["打鱼", "升级", "冲杯"]
        ).grid(row=0, column=1, sticky="ew")

        # 优先升级
        ttk.Label(config_frame, text="优先升级:").grid(row=1, column=0, sticky="w")
        self.priority_var = tk.StringVar(value="女王")
        ttk.Combobox(
            config_frame,
            textvariable=self.priority_var,
            values=["女王", "蛮王", "武器", "城墙"]
        ).grid(row=1, column=1, sticky="ew")

        # 其他选项
        self.keep_worker_var = tk.BooleanVar(value=True)
        ttk.Checkbutton(
            config_frame, 
            text="留一个工人", 
            variable=self.keep_worker_var
        ).grid(row=2, column=0, columnspan=2, sticky="w")

        self.auto_upgrade_var = tk.BooleanVar(value=True)
        ttk.Checkbutton(
            config_frame, 
            text="自动升级", 
            variable=self.auto_upgrade_var
        ).grid(row=3, column=0, columnspan=2, sticky="w")

        # 按钮组
        button_frame = ttk.Frame(config_frame)
        button_frame.grid(row=4, column=0, columnspan=2, pady=5)

        ttk.Button(button_frame, text="保存配置", command=self.save_config).pack(side="left", padx=5)
        ttk.Button(button_frame, text="开始任务", command=self.start_task).pack(side="left", padx=5)
        ttk.Button(button_frame, text="停止任务", command=self.stop_task).pack(side="left", padx=5)

    def setup_log_frame(self):
        """底部区域：操作记录"""
        log_frame = ttk.LabelFrame(self.root, text="操作记录", padding=10)
        log_frame.pack(fill="both", expand=True, padx=10, pady=5)

        self.log_text = scrolledtext.ScrolledText(
            log_frame, 
            wrap=tk.WORD, 
            state="disabled", 
            height=10,
            font=("Consolas", 10)
        )
        self.log_text.pack(fill="both", expand=True)

        # 日志颜色标签
        self.log_text.tag_config("info", foreground="blue")
        self.log_text.tag_config("success", foreground="green")
        self.log_text.tag_config("warning", foreground="orange")
        self.log_text.tag_config("error", foreground="red")

    def log_message(self, message, level="info"):
        """记录日志（线程安全）"""
        current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        self.log_queue.put((f"[{current_time}] {message}", level))

    def check_log_queue(self):
        """定时检查队列并更新日志（主线程安全）"""
        while not self.log_queue.empty():
            message, level = self.log_queue.get()
            self.log_text.configure(state="normal")
            self.log_text.insert(tk.END, message + "\n", level)
            self.log_text.configure(state="disabled")
            self.log_text.see(tk.END)  # 自动滚动到底部

        # 每隔100ms检查一次队列
        self.root.after(100, self.check_log_queue)

    def save_config(self):
        """保存配置"""
        mode = self.mode_var.get()
        priority = self.priority_var.get()
        self.log_message(f"保存配置: 模式={mode}, 优先升级={priority}", "success")

    def start_task(self):
        """开始模拟任务（多线程）"""
        self.task_running = True
        self.log_message("开始运行！", "info")

    def stop_task(self):
        """停止任务"""
        self.task_running = False
        self.log_message("任务已停止", "warning")



if __name__ == "__main__":
    root = tk.Tk()
    app = ClashManagerApp(root)
    root.mainloop() #